#include "public.h"




#ifdef WIN32


struct ThreadParam
{
	void *(*start_routine)(void*);
	void *arg;
};


static	DWORD WINAPI ThreadProc( LPVOID lpParam )
{
	struct ThreadParam *param = (struct ThreadParam*)lpParam;

	param->start_routine( param->arg );
	
	free( param );
	return 0;
}



int	pthread_create( pthread_t *thread, const pthread_attr_t *attr,
              void *(*start_routine)(void*), void *arg )
{
	DWORD ThreadID;
	struct ThreadParam *param = (struct ThreadParam *)malloc( sizeof(*param) );
	
	param->start_routine	= start_routine;
	param->arg		= arg;
	
	*thread = CreateThread( NULL, 0, ThreadProc, param, 0, &ThreadID );
	if( INVALID_HANDLE_VALUE == *thread )
		return EAGAIN;
	else
		return 0;
}


int pthread_cond_init( pthread_cond_t *cond, const pthread_condattr_t *attr )
{
	char	name[64];

	sprintf( name, "pthread_cond_%d_%p", g_cur_pid, cond );
	*cond = CreateEvent( NULL, FALSE, FALSE, name );
	if( INVALID_HANDLE_VALUE == *cond )
		return -1;
	else
		return 0;
}


int	pthread_cond_destroy( pthread_cond_t *cond )
{
	CloseHandle( *cond );
	return 0;
}


int	pthread_cond_wait( pthread_cond_t *cond, pthread_mutex_t *mutex )
{
	int nret;
	
	pthread_mutex_unlock( mutex );
	nret = WaitForSingleObject( cond, INFINITE );
	pthread_mutex_lock( mutex );

	if( WAIT_OBJECT_0 == nret )
		return 0;
	else
		return -1;
}


int	pthread_cond_signal( pthread_cond_t *cond ) 
{
	return SetEvent( cond )?0:-1;
}


#endif
